<template>
  <div class="login-container">
    <div class="login-card">
      <!-- 头部 -->
      <div class="login-header">
        <div class="logo">
          <img
            src="/images/logo.png"
            alt="CardCaptorSakura"
            class="logo-image"
          />
          <h1 class="logo-text">CardCaptorSakura</h1>
        </div>
        <p class="subtitle">多人格AI聊天助手</p>
      </div>

      <!-- 登录表单 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名或邮箱"
            size="large"
            prefix-icon="User"
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item>
          <div class="form-options">
            <el-checkbox v-model="loginForm.remember"> 记住我 </el-checkbox>
            <el-link type="primary" @click="showForgotPassword">
              忘记密码？
            </el-link>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? "登录中..." : "登录" }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 社交登录 -->
      <div class="social-login">
        <div class="divider">
          <span>或使用以下方式登录</span>
        </div>

        <div class="social-buttons">
          <el-button
            class="social-button google"
            @click="handleSocialLogin('google')"
          >
            <svg class="social-icon" viewBox="0 0 24 24">
              <path
                fill="#4285F4"
                d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
              />
              <path
                fill="#34A853"
                d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
              />
              <path
                fill="#FBBC05"
                d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
              />
              <path
                fill="#EA4335"
                d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
              />
            </svg>
            Google
          </el-button>

          <el-button
            class="social-button github"
            @click="handleSocialLogin('github')"
          >
            <svg class="social-icon" viewBox="0 0 24 24">
              <path
                fill="currentColor"
                d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"
              />
            </svg>
            GitHub
          </el-button>
        </div>
      </div>

      <!-- 注册链接 -->
      <div class="register-link">
        <span>还没有账号？</span>
        <el-link type="primary" @click="goToRegister"> 立即注册 </el-link>
      </div>
    </div>

    <!-- 忘记密码对话框 -->
    <el-dialog
      v-model="forgotPasswordVisible"
      title="重置密码"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="forgotPasswordFormRef"
        :model="forgotPasswordForm"
        :rules="forgotPasswordRules"
        label-width="80px"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="forgotPasswordForm.email"
            placeholder="请输入注册邮箱"
            clearable
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="forgotPasswordVisible = false"> 取消 </el-button>
          <el-button
            type="primary"
            :loading="sendingResetEmail"
            @click="handleForgotPassword"
          >
            {{ sendingResetEmail ? "发送中..." : "发送重置邮件" }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElForm } from "element-plus";
import { useAuth } from "@/composables/useAuth";
import { authApi } from "@/api/services";
import type { FormInstance, FormRules } from "element-plus";
import type { LoginRequest } from "@/types/user";

const router = useRouter();
const route = useRoute();
const { login, loading } = useAuth();

// 表单引用
const loginFormRef = ref<FormInstance>();
const forgotPasswordFormRef = ref<FormInstance>();

// 登录表单
const loginForm = reactive<LoginRequest>({
  username: "",
  password: "",
  remember: false,
});

// 忘记密码表单
const forgotPasswordForm = reactive({
  email: "",
});

// 状态
const forgotPasswordVisible = ref(false);
const sendingResetEmail = ref(false);

// 表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: "请输入用户名或邮箱", trigger: "blur" },
    { min: 3, message: "用户名至少3个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码至少6个字符", trigger: "blur" },
  ],
};

const forgotPasswordRules: FormRules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
};

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  try {
    const valid = await loginFormRef.value.validate();
    if (!valid) return;

    const success = await login(loginForm);
    if (success) {
      ElMessage.success("登录成功");
    }
  } catch {
    // 登录失败
  }
};

// 社交登录
const handleSocialLogin = (provider: "google" | "github") => {
  const baseUrl = import.meta.env.VITE_APP_BASE_API || "/api";
  const redirectUrl = encodeURIComponent(
    window.location.origin + "/auth/callback",
  );
  const socialLoginUrl = `${baseUrl}/auth/social/${provider}?redirect=${redirectUrl}`;

  window.location.href = socialLoginUrl;
};

// 显示忘记密码对话框
const showForgotPassword = () => {
  forgotPasswordVisible.value = true;
};

// 处理忘记密码
const handleForgotPassword = async () => {
  if (!forgotPasswordFormRef.value) return;

  try {
    const valid = await forgotPasswordFormRef.value.validate();
    if (!valid) return;

    sendingResetEmail.value = true;

    await sendPasswordResetEmail(forgotPasswordForm.email);

    ElMessage.success("重置邮件已发送，请查收邮箱");
    forgotPasswordVisible.value = false;
    forgotPasswordForm.email = "";
  } catch (error: any) {
    ElMessage.error(error.message || "发送重置邮件失败");
  } finally {
    sendingResetEmail.value = false;
  }
};

// 跳转到注册页
const goToRegister = () => {
  router.push("/register");
};

// 组件挂载时检查URL参数
onMounted(() => {
  // 检查是否有错误信息
  const error = route.query.error as string;
  if (error) {
    ElMessage.error(decodeURIComponent(error));
  }

  // 检查是否有成功信息
  const success = route.query.success as string;
  if (success) {
    ElMessage.success(decodeURIComponent(success));
  }
});
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  background: var(--el-bg-color);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 40px;
  backdrop-filter: blur(10px);
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 8px;
}

.logo-image {
  width: 48px;
  height: 48px;
  border-radius: 8px;
}

.logo-text {
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
}

.subtitle {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin: 0;
}

.login-form {
  margin-bottom: 24px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
}

.social-login {
  margin-bottom: 24px;
}

.divider {
  position: relative;
  text-align: center;
  margin: 24px 0;
}

.divider::before {
  content: "";
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: var(--el-border-color);
}

.divider span {
  background: var(--el-bg-color);
  padding: 0 16px;
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

.social-buttons {
  display: flex;
  gap: 12px;
}

.social-button {
  flex: 1;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  border: 1px solid var(--el-border-color);
  background: var(--el-bg-color);
  color: var(--el-text-color-primary);
  transition: all 0.3s;
}

.social-button:hover {
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

.social-button.google:hover {
  border-color: #4285f4;
  color: #4285f4;
}

.social-button.github:hover {
  border-color: #333;
  color: #333;
}

.social-icon {
  width: 18px;
  height: 18px;
}

.register-link {
  text-align: center;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.register-link .el-link {
  margin-left: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    padding: 24px;
    margin: 0 16px;
  }

  .logo-text {
    font-size: 20px;
  }

  .social-buttons {
    flex-direction: column;
  }
}

/* 暗色主题适配 */
.dark .login-container {
  background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
}

.dark .social-button.github:hover {
  border-color: #f7fafc;
  color: #f7fafc;
}
</style>
